import {
  Controller,
  Post,
  UseInterceptors,
  UploadedFile,
  Body,
  Get,
  Param,
  Query,
  Delete,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { ArticleService } from './article.service';
import { VectorService } from './vector.service';
import { diskStorage } from 'multer';
import * as path from 'path';
import { Public } from 'src/auth/auth.decorator';

@Controller('article')
export class ArticleController {
  constructor(
    private readonly articleService: ArticleService,
    private readonly vectorService: VectorService,
  ) {}

  @Post('upload')
  @Public(true)
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: './uploads',
        filename: (req, file, cb) => {
          const ext = path.extname(file.originalname);
          const filename = `${Date.now()}-${Math.round(Math.random() * 1e9)}${ext}`;
          cb(null, filename);
        },
      }),
      fileFilter: (req, file, cb) => {
        const allowed = [
          'text/plain',
          'application/pdf',
          'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        ];
        if (allowed.includes(file.mimetype)) {
          cb(null, true);
        } else {
          cb(new Error('仅支持 txt、pdf、docx 文件'), false);
        }
      },
    }),
  )
  async uploadArticle(@UploadedFile() file: Express.Multer.File, @Body('title') title: string) {
    const content = await this.articleService.parseFile(file.path, file.mimetype);
    const article = await this.articleService.createArticle(title || file.originalname, content, file.originalname);
    return { success: true, article };
  }

  @Get()
  @Public(true)
  async getArticles() {
    return this.articleService.findAll();
  }

  @Get(':id')
  @Public(true)
  async getArticle(@Param('id') id: string) {
    return this.articleService.getArticleWithChunkCount(Number(id));
  }

  @Delete(':id')
  @Public(true)
  async deleteArticle(@Param('id') id: string) {
    return this.articleService.deleteArticle(Number(id));
  }

  @Post('search')
  @Public(true)
  async searchDocuments(@Body('query') query: string, @Body('limit') limit: number = 5) {
    if (!query) {
      return { error: '查询内容不能为空' };
    }

    try {
      const results = await this.vectorService.similaritySearch(query, limit);
      
      // 格式化搜索结果
      const formattedResults = results.map(chunk => ({
        id: chunk.id,
        content: chunk.content,
        similarity: chunk.metadata?.similarity || 0,
        article: {
          id: chunk.article.id,
          title: chunk.article.title,
          filename: chunk.article.filename,
        },
        metadata: chunk.metadata,
      }));

      return {
        success: true,
        query,
        results: formattedResults,
        total: formattedResults.length,
      };
    } catch (error) {
      return {
        success: false,
        error: error.message,
      };
    }
  }

  @Get('stats/chunks')
  @Public(true)
  async getChunkStats() {
    try {
      const articles = await this.articleService.findAll();
      const stats = await Promise.all(
        articles.map(async (article) => {
          const chunkCount = await this.vectorService.getDocumentChunkCount(article.id);
          return {
            id: article.id,
            title: article.title,
            filename: article.filename,
            chunkCount,
            uploadTime: article.uploadTime,
          };
        })
      );

      return {
        success: true,
        stats,
        totalArticles: stats.length,
        totalChunks: stats.reduce((sum, article) => sum + article.chunkCount, 0),
      };
    } catch (error) {
      return {
        success: false,
        error: error.message,
      };
    }
  }
} 